﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.SqlClient;
using System.Data;

namespace BaccaratRally.DataKernel.Service
{
    using BaccaratRally.DataKernel.SqlGateway;
    using BaccaratRally.DataKernel.Entity;

    public class AccountService : ServiceBase
    {
        public virtual Account Create(Account newItem)
        {
            return SqlGateway.CreateInstance().Insert<Account>(newItem);
        }

        public virtual Account Update(Account item)
        {
            return SqlGateway.CreateInstance().Update<Account>(item);
        }

        public virtual List<Account> GetAccountList()
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("SELECT * FROM Account");

            return SqlGateway.CreateInstance().Select<Account>(sqlstring.ToString(), CommandType.Text).ToList();
        }

        public virtual List<Account> GetAccount(String accountName)
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("SELECT * FROM dbo.[Account] where AccountName = '" + accountName + "' Order By AccountPos ");

            return SqlGateway.CreateInstance().Select<Account>(sqlstring.ToString(), CommandType.Text).ToList();
        }

        public virtual Account GetAccount(String accountName, String accountPos)
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("SELECT * FROM dbo.[Account] where AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "'");

            return SqlGateway.CreateInstance().SelectSingle<Account>(sqlstring.ToString(), CommandType.Text);
        }

        public virtual void KeepAlive(String accountName, String accountPos, String site, String ipAddress, Byte tableStatus1, Byte tableStatus2, Byte tableStatus3)
        {
            Account curraccount = this.GetAccount(accountName, accountPos);

            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("UPDATE Account SET CurrSite = '" + site + "', IPAddress = '" + ipAddress + "', Online = 1, LastActive = getdate() WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "' ");

            if (tableStatus1 != curraccount.TableStatus1)
            {
                sqlstring.Append("UPDATE Account SET TableStatus1  = " + tableStatus1 + ", LastChangeTime1 = getdate() WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "'  ");
            }

            if (tableStatus2 != curraccount.TableStatus2)
            {
                sqlstring.Append("UPDATE Account SET TableStatus2 = " + tableStatus2 + ", LastChangeTime2 = getdate() WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "'  ");
            }

            if (tableStatus3 != curraccount.TableStatus3)
            {
                sqlstring.Append("UPDATE Account SET TableStatus3 = " + tableStatus3 + ", LastChangeTime3 = getdate() WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "'  ");
            }

            SqlGateway.CreateInstance().ExecuteNonQuery(sqlstring.ToString(), CommandType.Text);

            if (tableStatus1 != curraccount.TableStatus1 && tableStatus1 == 1) { CheckOtherSide(accountName, accountPos, 1); }
            if (tableStatus2 != curraccount.TableStatus2 && tableStatus2 == 1) { CheckOtherSide(accountName, accountPos, 2); }
            if (tableStatus3 != curraccount.TableStatus3 && tableStatus3 == 1) { CheckOtherSide(accountName, accountPos, 3); }
        }

        public virtual void CheckOtherSide(String accountName, String accountPos, Byte tableNo)
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("SELECT LastChangeTime" + tableNo.ToString() + " FROM Account WHERE AccountName = '" + accountName + "' and AccountPos <> '" + accountPos + "' and TableStatus" + tableNo.ToString() + " = 1 ");
            sqlstring.Append("SELECT LastChangeTime" + tableNo.ToString() + " FROM Account WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "' and TableStatus" + tableNo.ToString() + " = 1 ");


            DataSet ds = SqlGateway.CreateInstance().SelectDataSet(sqlstring.ToString(), CommandType.Text);


            if (ds.Tables[0].Rows.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                double offset = ((DateTime)ds.Tables[0].Rows[0][0] - (DateTime)ds.Tables[1].Rows[0][0]).TotalSeconds;
                if (offset < 5 && offset > -5)
                {
                    UserService uservice = ServiceFactory.CreateService<UserService>();
                    User user = uservice.GetUser(accountName);

                    Decimal basesize = Decimal.Parse(user.UserSetting.Split(new char[] { ',' })[0]);
                    double riseratelow = double.Parse(user.UserSetting.Split(new char[] { ',' })[2]);
                    Decimal risesizemin = Decimal.Parse(user.UserSetting.Split(new char[] { ',' })[1]);

                    double riseratehigh = double.Parse(user.UserSetting.Split(new char[] { ',' })[4]);
                    Decimal risesizemax = Decimal.Parse(user.UserSetting.Split(new char[] { ',' })[3]);

                    Random r = new Random(Guid.NewGuid().GetHashCode());
                    double rd = r.NextDouble();
                    if (rd < riseratelow) basesize = risesizemin;
                    if (rd > riseratehigh) basesize = risesizemax;

                    Random rbd = new Random(Guid.NewGuid().GetHashCode());
                    double rbdr = rbd.NextDouble();
                    double xrate = double.Parse(user.UserSetting.Split(new char[] { ',' })[5]);
                    if (accountPos == "A") xrate = 1 - xrate;

                    String betdirectionA = (rbdr > xrate) ? "B" : "V";
                    String betdirectionB = (betdirectionA == "B") ? "V" : "B";

                    BetItemService bis = ServiceFactory.CreateService<BetItemService>();
                    bis.Create(new BetItem() { AccountName = accountName, AccountPos = accountPos, TableNo = tableNo, BetDirection = betdirectionA, BetSize = basesize, BetTime = ((accountPos == "A") ? DateTime.Now : DateTime.Now.AddSeconds(2)) });
                    bis.Create(new BetItem() { AccountName = accountName, AccountPos = (accountPos == "A") ? "B" : "A", TableNo = tableNo, BetDirection = betdirectionB, BetSize = basesize, BetTime = ((accountPos == "A") ? DateTime.Now.AddSeconds(2) : DateTime.Now) });
                    
                }
            }
        }

        public virtual void OnStart(String accountName, String accountPos)
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("UPDATE Account SET [Online] = 1 , [TableStatus1] = 1 ,[LastChangeTime1] = DATEADD(ss,-20,getdate()),[TableStatus2] = 1,[LastChangeTime2] = DATEADD(ss,-20,getdate()),[TableStatus3] = 1,[LastChangeTime3] = DATEADD(ss,-20,getdate()) where AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "' ");
            sqlstring.Append("UPDATE Bets SET BetStatus = 9 where AccountName = '" + accountName + "' and betstatus < 6  and AccountPos = '" + accountPos + "' ");
            sqlstring.Append("UPDATE Account SET [Online] = 1  where AccountName = '" + accountName + "'");

            SqlGateway.CreateInstance().ExecuteNonQuery(sqlstring.ToString(), CommandType.Text);
        }

        public virtual Byte CheckOnline(String accountName, String accountPos, Byte online)
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("UPDATE [Account] SET Online = " + online.ToString() + " WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "' and Online = 1 ");
            SqlGateway.CreateInstance().ExecuteNonQuery(sqlstring.ToString(), CommandType.Text);

            accountPos = (accountPos == "A") ? "B" : "A";
            StringBuilder sqlstring1 = new StringBuilder();
            sqlstring1.Append("SELECT * FROM [Account] WHERE AccountName = '" + accountName + "' and AccountPos = '" + accountPos + "' ");

            return SqlGateway.CreateInstance().SelectSingle<Account>(sqlstring1.ToString(), CommandType.Text).Online;
        }

        public virtual void AccountLogout()
        {
            StringBuilder sqlstring = new StringBuilder();
            sqlstring.Append("UPDATE Account SET Online = 0 WHERE Online = 1 and datediff(ss,LastActive,getdate()) > 15 ");

            SqlGateway.CreateInstance().ExecuteNonQuery(sqlstring.ToString(), CommandType.Text);
        }
    }
}
